from rest_framework import serializers
from users.models import User
from django.contrib.auth.hashers import make_password

class UserModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = [
            'id',
            'username',
            'mobile',
            'email',
            'password',
        ]

    def validate(self, attrs):
        password = attrs.get('password')
        attrs['password'] = make_password(password)
        attrs['is_staff'] = True

        return attrs

    # def create(self, validated_data):
    #     password = validated_data.get('password')
    #     validated_data['password'] = make_password(password)
    #     validated_data['is_staff'] = True
    #     instance = self.Meta.model.objects.create(**validated_data)
    #
    #     return self.Meta.model.objects.create(**validated_data)

    def create(self, validated_data):
        # User.objects.create_user(**validated_data) 将密码加密
        return User.objects.create_superuser(**validated_data)  # 密码加密，设置超级管理员